package com.dy.scs.controller;

import com.dy.scs.mapper.StudentMapper;
import com.dy.scs.pojo.Result;
import com.dy.scs.pojo.Student;
import com.dy.scs.service.StudentService;
import com.dy.scs.service.uploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.UUID;

import static java.lang.Integer.parseInt;

/**
 * 文件
 */
@RestController
@RequestMapping("/upload")
public class uploadController {

    @Autowired
    private uploadService uploadService;

    /**
     * 上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename= file.getOriginalFilename();
        String newFilename= UUID.randomUUID() +originalFilename.substring(originalFilename.lastIndexOf("."));
        file.transferTo(new File("D:\\spring\\scs\\file\\"+newFilename));

        File tempFile = new File("D:\\spring\\scs\\file\\" + newFilename);
        //file.transferTo(tempFile);

        // 读取文件内容
        try (BufferedReader br = new BufferedReader(new FileReader(tempFile))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("，");
                if (parts.length == 5) {
                    Student person = new Student(parts[0], parts[1], parts[2],Integer.parseInt(parts[3]),parts[4]);
                    uploadService.save(person);
                }
            }
        }

        // 删除临时文件（可选）
        tempFile.delete();

        return Result.success();
    }
}
